package cn.tworice.common.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    public static <T> void exportExcelTemplate(HttpServletResponse response,Class<T> clazz) throws IOException {
        exportExcel(response, clazz, "模板",new ArrayList<>());
    }

    public static <T> void exportExcelData(HttpServletResponse response,Class<T> clazz,List<T> data) throws IOException {
        exportExcel(response, clazz, "批量导出", data);
    }

    public static <T> void exportExcel(HttpServletResponse response, Class<T> clazz, String fileName, List<T> data) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和EasyExcel没有关系
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度，自动适配。最大 255 宽度
                .sheet("模板")
                .doWrite(data);
    }
}
